from rest_framework import serializers

from apps.headlines.models import Article
from apps.questions.models import Label, Question, Reply
from apps.recruit.models import Enterprise
from apps.users.models import User


class LabelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = ['id', 'label_name']


class QuestionSerializer(serializers.ModelSerializer):
    labels = serializers.StringRelatedField()

    class Meta:
        model = Question
        fields = ['id', 'createtime', 'labels', 'reply', 'replyname', 'replytime', 'title', 'unuseful_count',
                  'useful_count', 'user', 'visits']


class UsernameSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'avatar']


class ReplySerializer(serializers.ModelSerializer):
    user = UsernameSerializer()

    class Meta:
        model = Reply
        fields = ['id', 'content', 'createtime', 'useful_count', 'problem', 'unuseful_count', 'subs', 'user', 'parent']


class ArticlesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title']


class UserFanSerializer(serializers.ModelSerializer):
    articles = ArticlesSerializer(many=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'avatar', 'articles', 'fans']


class ArticleSerializer(serializers.ModelSerializer):
    user = UserFanSerializer(many=True)
    collected = serializers.BooleanField()

    class Meta:
        model = Article
        fields = ['id', 'title', 'content', 'createtime', 'user', 'collected_users', 'collected', 'image']


class Enterpriseerializer(serializers.ModelSerializer):
    recruits = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Enterprise
        fields = ['id', 'name', 'labels', 'logo', 'recruits', 'summary']


class UserSerializer(serializers.ModelSerializer):
    labels = LabelSerializer(many=True,read_only=True)
    questions = QuestionSerializer(many=True,read_only=True)
    answer_question = ReplySerializer(many=True,read_only=True)
    collected_articles = ArticleSerializer(many=True,read_only=True)
    enterpises = Enterpriseerializer(many=True,read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'realname', 'birthday', 'sex', 'avatar', 'website', 'email', 'city',
                  'address', 'labels', 'questions', 'answer_question', 'collected_articles', 'enterpises']
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {'read_only': True},
        }


class UserPasswordSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['password']

    def update(self, instance, validated_data):
        instance.set_password(validated_data['password'])
        instance.save()
        return instance
